package org.bouncycastle.openssl.test;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Util {
	public static long readLongLittleEndianFromEightBytes(byte [] data, int startPoint) {
		long result = 0L;

		for (int i = 0; i < 8; i++) {
			result += ((long) (data[startPoint + i] & 0xFF) << (8 * i));
		}

		return result;
	}

	public static long readLongLittleEndianFromFourBytes(byte [] data, int startPoint) {
		return ((long) (data[startPoint + 3] & 0xFF) << 24) + ((long) (data[startPoint + 2] & 0xFF) << 16) 
				+ ((long) (data[startPoint + 1] & 0xFF) << 8) + ((long) (data[startPoint] & 0xFF)) ;
	}

	public static int readIntLittleEndianFromTwoBytes(byte[] data, int startPoint) {
		return ((int) (data[startPoint + 1] & 0xFF) << 8) + ((int) (data[startPoint] & 0xFF)) ;
	}
	
	/**
	 * Apply SHA-256 hashing algorithm twice to specified array
	 * returns a new array containing the hashed data
	 * @param arr
	 * @return
	 */
	public static byte[] dHash(byte[] arr) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		byte[] hash = digest.digest(digest.digest(arr));		  
		return hash;
	}
	
	
	
	public static void printByteArrayAsHex(String arrayName, byte [] arr) {
		  System.out.println(arrayName + ":");
		  for (byte b : arr) {
			  System.out.format("%02X ", b);
		  }
		  System.out.println();
	  }
	
	public static String getPackedHexStringFromBytes(byte [] bytes) {		  
		  StringBuilder sb = new StringBuilder();
		    for (byte b : bytes) {
		        sb.append(String.format("%02X", b));
		    }
		  return sb.toString();
	  }
}
